<?php

use Biz\cache\IkeaActivity\IkeaActivityCache;
use Biz\model\IkeaActivity\IkeaActivityJoinRecordModel;
use Biz\model\IkeaActivity\IkeaActivityWinnerListModel;
use Biz\service\brand\Brand;
use Doraemon\cache\PhotoCounter;
use Doraemon\cache\UserCounter;
use Doraemon\model\Blank;
use Doraemon\model\Photos;
use Doraemon\service\Follow;
use Doraemon\service\Like;
use Doraemon\service\statSign\Basic as basicStatSign;
use Doraemon\service\TopicActivity;
use Doraemon\service\User;
use Doraemon\tools\BlockType;
use Doraemon\tools\ImgUrl;

class IndexAction extends ActionPlugin
{
    const USER_LEVEL = self::LEVEL_NOTHING;

    /**
     * @throws \Exception
     */
    public function main()
    {
        $currentUid = $this->uid;
        //查询头部需要展示的品牌数据
        $brandInfo = Brand::getBrandInfoByIds4Goods([IkeaActivityJoinRecordModel::BRAND_ID])[IkeaActivityJoinRecordModel::BRAND_ID] ?? [];
        if ($brandInfo) {
            $brandInfo['fans'] = UserCounter::getOneByType($brandInfo['uid'], UserCounter::TYPE_FANS) ?? 0;
            $brandInfo['is_follow'] = Follow::FollowStatus($currentUid,
                    $brandInfo['uid'])[$brandInfo['uid']] ?? 0;//1已关注该用户 0未关注
        }

        $noteIds = IkeaActivityJoinRecordModel::NOTE_ID_MAP;

        //查询需要展示的被点赞的内容
        $photoCounter = PhotoCounter::getMulti($noteIds);
        $isLikedMulti = Like::isLikedMulti($currentUid, $noteIds,
            \Doraemon\model\Like::LIKE_TYPE_PHOTO);//是否点赞了
        $contentList = [];
        $taskStatus = false; //该用户是否完成了点赞任务（因为在详情页里面点赞的情况）

        //查询内容数据
        $noteLists = Photos::getPhotoInfoTime($noteIds,
            ['id(obj_id)', 'title', 'remark', 'pic_id(cover_pic_id)', 'addtime', 'uid']) ?: [];
        $userList = User::getBatchBasicUserInfo(array_column($noteLists, 'uid'));
        $userListMap = array_column($userList, null, 'uid');
    

        foreach ($noteLists as $note) {
            $isLike = $isLikedMulti[$note['obj_id']] ?? 0;
            if ($isLike == 1) {
                $taskStatus = true;
            }
            $contentList [] = [
                'note_id' => $note['obj_id'],
                'nick' => $userListMap[$note['uid']]['nick'] ?? '',
                'avatar' => $userListMap[$note['uid']]['avatar'] ?? '',
                'title' => $note['title'] ?? '',
                'remark' => $note['remark'] ?? '',
                'cover_pic_url' => ImgUrl::getUrl(ImgUrl::APPTYPE_APP, $note['cover_pic_id'],
                    ImgUrl::IMAGE_SIZE_ORI_NPHONE),
                'like' => $photoCounter[$note['obj_id']]['like'],
                'is_like' => $isLike,
                'statSign' => basicStatSign::genStatSign(basicStatSign::MODULE_IKEA_NEWYEAR_NOTE, [
                    basicStatSign::EXTEND_KEY_OBJ_TYPE => BlockType::TYPE_PHOTO,
                    basicStatSign::EXTEND_KEY_OBJ_ID => $note['obj_id'],
                ], []),
            ];
        }
        $contentListRes = [];

        $contentListMap = array_column($contentList , null , 'note_id');
        
        foreach ($noteIds as $valNoteId){

            $contentListRes[] = $contentListMap[$valNoteId];
        }

        $taskMap = IkeaActivityJoinRecordModel::TASK_MAP;
        if(date('Ymd') >=$taskMap[3]['start_time'] &&  $taskStatus){ //只有用户对内容点赞了并且这个活动已经开始情况下 会自动完成任务4
            $map = [
                'uid' => $currentUid,
                'task_id' => 4,
                'type' => IkeaActivityJoinRecordModel::TYPE_TASK,
                'status' => IkeaActivityJoinRecordModel::STATUS_NORMAL,
            ];
            $info = IkeaActivityJoinRecordModel::getByWhere($map);
            if (empty($info)) {
                IkeaActivityJoinRecordModel::insertData($map);
            }
        }
        //组装任务数据
        $taskList = [];
        list($tasksComplete, $remind) = self::getMapByUid($currentUid);
        foreach ($taskMap as $task) {
            $task['is_set_remind'] = 0;//1已设置过日历提醒 0未设置
            if (isset($remind[$task['task_id']]) && !empty($remind[$task['task_id']])) {
                $task['is_set_remind'] = 1;//1已设置过日历提醒 0未设置
            }
            $task['task_status'] = 0;//1已完成 0未完成
            if (isset($tasksComplete[$task['task_id']]) && !empty($tasksComplete[$task['task_id']])) {
                $task['task_status'] = 1;//1已完成 0未完成
            }
            $task['task_detail'] = '';//任务详情
            $task['blank_info'] = [];//文章详情
            $task['topic_info'] = [];//话题详情
            $task['content_list'] = [];//点赞任务里面的内容

            switch ($task['task_id']) {
                case 2://文章详情
                    $task['blank_info']=[
                        'obj_id' => '',
                        'statSign' => '',
                    ];
                    break;
                case 3: //话题详情
                    $topicId = IkeaActivityJoinRecordModel::TOPIC_ID;
                    $topicInfo = TopicActivity::getTopicInfosForList([$topicId])[$topicId]['topic']['topic_info'] ?? [];
                    $task['topic_info'] = [
                        'topic_id' => $topicId,
                        'title' => $topicInfo['title'] ?? '',
                        'cover_pic_url' => $topicInfo['cover_pic_url'] ?? '',
                        'channel_tag' => $topicInfo['channel_tag'] ?? '',
                        'is_light_topic' => 0,//是否是轻话题  1:轻话题 0:话题
                        'statSign' => basicStatSign::genStatSign(basicStatSign::MODULE_IKEA_NEWYEAR_TOPIC_CARD, [
                            basicStatSign::EXTEND_KEY_OBJ_TYPE => BlockType::TYPE_TOPIC_ACTIVITY,
                            basicStatSign::EXTEND_KEY_OBJ_ID => $topicId,
                        ], []),
                    ];
                    break;
                case 4: //note列表
                    $task['content_list'] = $contentListRes;
                    break;
                case 5://屏保图片
                    $task['task_detail'] = $tasksComplete[$task['task_id']]['task_detail'] ?? '';
                    break;
                default:
            }


            $taskList[] = $task;
        }
        //组装中奖相关数据  是否中奖，是否已填写收货地址
        $hasAddress = IkeaActivityWinnerListModel::getByWhere([
            'uid' => $currentUid,
            'status' => IkeaActivityWinnerListModel::STATUS_NORMAL,
        ]);
        if (empty($hasAddress)) {
            $drawInfo['has_address'] = 0; //0未填写收货地址 1已填写收货地址
        } else {
            $drawInfo['has_address'] = 1; //0未填写收货地址 1已填写收货地址
        }

        $drawInfo['is_winner'] = (int)(in_array($currentUid, IkeaActivityCache::getData())); //1 已中奖 0未中奖
        $this->setSuccess(compact('brandInfo', 'taskList', 'drawInfo'), self::API_CODE_SUCCES);

    }

    public static function getMapByUid($uid): array
    {
        $records = IkeaActivityJoinRecordModel::selectByWhere([
            'uid' => $uid,
            'status' => IkeaActivityJoinRecordModel::STATUS_NORMAL,
        ]);
        $tasks = []; // 存放任务数据
        $remind = []; // 存放日历提醒数据
        if ($records) {
            foreach ($records as $record) {
                if (IkeaActivityJoinRecordModel::TYPE_TASK == $record['type']) {
                    $tasks[] = $record;
                } else {
                    $remind[] = $record;
                }
            }
        }

        return [array_column($tasks, null, 'task_id'), array_column($remind, null, 'task_id')];

    }
}